import { View, Text, Image, Input, Button, ScrollView } from '@tarojs/components'
import { useLoad, useRouter } from '@tarojs/taro'
import { useState, useRef, useEffect } from 'react'
import './index.css'

const mockMerchants = {
  '1': { name: '商家A', avatar: 'https://placekitten.com/80/80' },
  '2': { name: '商家B', avatar: 'https://placekitten.com/81/81' },
  '3': { name: '商家C', avatar: 'https://placekitten.com/82/82' },
}

const mockMessages = [
  { id: 'm1', from: 'merchant', content: '您好，有什么可以帮您？', time: '14:32' },
  { id: 'm2', from: 'user', content: '我想咨询一下订单情况', time: '14:33' },
  { id: 'm3', from: 'merchant', content: '您的订单已发货，预计明天送达。', time: '14:34' },
]

export default function Chat() {
  const router = useRouter()
  const merchantId = router.params.merchantId || '1'
  const merchant = mockMerchants[merchantId] || { name: '未知商家', avatar: '' }

  const [messages, setMessages] = useState(mockMessages)
  const [inputValue, setInputValue] = useState('')
  const scrollViewRef = useRef(null)

  useLoad(() => {
    // 可在此处请求消息记录
  })

  useEffect(() => {
    // 新消息时自动滚动到底部
    if (scrollViewRef.current) {
      // @ts-ignore
      scrollViewRef.current.scrollTop = 99999
    }
  }, [messages])

  const handleInput = (e) => {
    setInputValue(e.detail.value)
  }

  const handleSend = () => {
    if (!inputValue.trim()) return
    setMessages([
      ...messages,
      { id: `m${messages.length + 1}`, from: 'user', content: inputValue, time: '14:35' },
    ])
    setInputValue('')
  }

  return (
    <View className='chat-container'>
      <View className='chat-header'>
        <Image className='chat-avatar' src={merchant.avatar} />
        <Text className='chat-title'>{merchant.name}</Text>
      </View>
      <ScrollView
        className='chat-messages'
        scrollY
        ref={scrollViewRef}
      >
        {messages.map((msg) => (
          <View
            key={msg.id}
            className={`chat-message-row ${msg.from === 'user' ? 'chat-message-user' : 'chat-message-merchant'}`}
          >
            {msg.from === 'merchant' && <Image className='chat-bubble-avatar' src={merchant.avatar} />}
            <View className={`chat-bubble ${msg.from}`}>{msg.content}</View>
            {msg.from === 'user' && <View className='chat-bubble-avatar chat-bubble-avatar-user'></View>}
          </View>
        ))}
      </ScrollView>
      <View className='chat-input-bar'>
        <Input
          className='chat-input'
          value={inputValue}
          onInput={handleInput}
          placeholder='请输入消息...'
          confirmType='send'
          onConfirm={handleSend}
        />
        <Button className='chat-send-btn' onClick={handleSend}>
          发送
        </Button>
      </View>
    </View>
  )
} 